package fr.inria.phoenix.scenario.bwsnfirefighting.impl.context;

import fr.inria.diagen.core.ServiceConfiguration;
import fr.inria.diagen.core.exception.InvocationException;
import fr.inria.phoenix.scenario.bwsnfirefighting.framework.distributed.smokedetection.EnvironmentSensorDeviceComposite;
import fr.inria.phoenix.scenario.bwsnfirefighting.framework.distributed.smokedetection.EnvironmentSensorDeviceProxy;
import fr.inria.phoenix.scenario.bwsnfirefighting.framework.distributed.smokedetection.SmokeDetection;

public class SmokeDetectionImpl extends SmokeDetection {

	public SmokeDetectionImpl(ServiceConfiguration serviceConfiguration) {
		super(serviceConfiguration);
	}

	@Override
	public void onNewSmoke(EnvironmentSensorDeviceProxy proxy,
			Boolean newSmokeValue) {
		EnvironmentSensorDeviceComposite sensors = discover(environmentSensorDevicesWhere().location(proxy.getLocation()));
		try {
			if (proxy.getDangerousmaterial()){
				Boolean temp = false;
				for (EnvironmentSensorDeviceProxy sensor : sensors){
					if(sensor.getSmoke()){
						temp = true;
					}
				}
				this.setSmokeDetection(newSmokeValue || temp, proxy.getLocation());
			}
			else{
				if (sensors.size() < 4){
					Boolean temp = false;
					for (EnvironmentSensorDeviceProxy sensor : sensors){
						if(sensor.getSmoke()){
							temp = true;
						}
					}
					this.setSmokeDetection(newSmokeValue || temp, proxy.getLocation());
				}
				else{
					int count = newSmokeValue ? 1 : 0;
					for (EnvironmentSensorDeviceProxy sensor : sensors){
						if(sensor.getSmoke()){
							count++;
						}
					}
					this.setSmokeDetection(count > 3, proxy.getLocation());
				}
			}
		} catch (InvocationException e) {
			e.printStackTrace();
		}
	}

}
